package net.awpspace.walkman.view;

import net.awpspace.walkman.entity.MP3;
import net.awpspace.walkman.utils.BackStack;
import net.awpspace.walkman.utils.Loader;

import com.sun.lwuit.Command;
import com.sun.lwuit.Form;
import com.sun.lwuit.List;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BoxLayout;

/**
 * Screen: Library
 * 
 * @author Diep AwpSpace
 * 
 */
public class Library extends Form implements ActionListener {

	private List list;

	private Command update;
	private Command back;

	public Library() {
		super();
		setTitle("Library");
		setLayout(new BoxLayout(BoxLayout.Y_AXIS));

		update = new Command("update");
		back = new Command("back");
		addCommand(update);
		addCommand(back);
		addCommandListener(this);

		list = new List();
		list.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent evt) {
				Playing.track = (MP3) Loader.musics.elementAt(list
						.getSelectedIndex());
				BackStack.getInstance(null).back();
				BackStack.getInstance(null).forward(new Playing(true));
			}
		});
		notifyUpdated();
		addComponent(list);
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getCommand().equals(back)) {
			BackStack.getInstance(null).back();
		} else {
			new Thread() {

				public void run() {
					Loader.updateLibrary();
					notifyUpdated();
				}
			}.start();
		}
	}

	/**
	 * Library has been updated
	 */
	private void notifyUpdated() {
		for (int i = 0; i < list.size(); ++i) {
			list.getModel().removeItem(i);
		}
		for (int i = 0; i < Loader.musics.size(); ++i) {
			String title = ((MP3) Loader.musics.elementAt(i)).title;
			list.addItem(title != null ? title : ((MP3) Loader.musics
					.elementAt(i)).filePath);
		}
	}
}
